/*
 * vector.c
 *
 *  Created on: Jun 18, 2010
 *      Author: Guilherme
 */

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include "vector.h"

vector_t *init_vector(int size) {
	vector_t *v;

	if ((v = malloc(sizeof(vector_t))) == NULL) {
		fprintf(stderr, "Malloc failure! Could not create a new vector\n");
		exit(2);
	}
	if ((v->elements = calloc(size + 1, sizeof(vector_element_t *))) == NULL) {
		fprintf(stderr, "Calloc failure! Could not create vector elements\n");
		exit(2);
	}
	v->size = size;
	v->current_size = 0;

	return v;
}

void insert_element(vector_t *v, vector_element_t *e) {
	v->elements[e->nodeID] = e;
	v->current_size++;
}

int find_min(vector_t *v) {
	distance min_distance = INT_MAX;
	int min_position = 0;
	int i;

	if (is_empty(v)) {
		fprintf(stderr, "Vector is empty!\n");
		exit(2);
	}
	for (i = 1; i <= v->size; i++) {
		// element was not deleted (different from -1)
		if (v->elements[i]->distance != -1 && v->elements[i]->distance < min_distance) {
			min_position = i;
			min_distance = v->elements[i]->distance;
		}
	}

	return min_position;
}

vector_element_t *delete_min(vector_t *v) {
	int position;

	position = find_min(v);
	v->elements[position]->distance = -1;
	v->current_size--;

	return v->elements[position];
}

void decrease_key(vector_t *v, int nodeID, distance newDistance) {
	v->elements[nodeID]->distance = newDistance;
}

int is_empty(vector_t *v) {
	return v->current_size == 0;
}

void destroy_vector(vector_t *v) {
	int i;

	for (i = 0; i <= v->size; i++) {
		free(v->elements[i]);
	}
	free(v->elements);
	free(v);
}
